/*
 * Android Runner is a multiplayer GPS game fully written by Xurxo Mendez Perez
 * 
 * Copyright (C) 2009 Xurxo Mendez Perez
 *   
 * This file is part of Android Runner.
 * 
 * Android Runner is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * Android Runner is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with Android Runner.  If not, see <http://www.gnu.org/licenses/>.
 */

package es.sonxurxo.gpsgame.client.cv.activity;

import android.app.Activity;
import android.app.Dialog;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import es.sonxurxo.gpsgame.client.R;
import es.sonxurxo.gpsgame.client.cv.common.actions.CommonActions;
import es.sonxurxo.gpsgame.client.cv.common.dialogs.CommonDialogs;
import es.sonxurxo.gpsgame.client.cv.util.constants.CustomResultCodes;
import es.sonxurxo.gpsgame.client.model.service.player.HttpPlayerServiceImpl;
import es.sonxurxo.gpsgame.client.model.service.to.FinishedGame;
import es.sonxurxo.gpsgame.client.model.service.to.Player;
import es.sonxurxo.gpsgame.client.util.DateOperations;
import es.sonxurxo.gpsgame.client.util.exception.ServerException;

/**
 * 
 * @author "Xurxo Mendez Perez"
 *
 */
public class ViewHistoryActivity extends Activity {

	private static final int LOGOUT_ID = Menu.FIRST;
	
    private Player player;
    
    private TableLayout table1;
    private TextView gameIdView, gameCityView, gameStartDateView;
    private FinishedGame [] fgList = new FinishedGame [0];
    private Button nextButton, previousButton;
    private long gameId;
    
    private GetHistoryTask getHistoryTask;
    
    private class NextOnClickListener implements OnClickListener {

    	private int gameNumber;

    	NextOnClickListener(int gameNumber) {
    		this.gameNumber = gameNumber;
    	}
		public void onClick(View v) {
			fillGameData(gameNumber);
		}
    }
    
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        setContentView(R.layout.view_history_page);
        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title_1);
        
        Bundle extras = getIntent().getExtras();
        player = (Player)extras.getSerializable("player");
        gameId = extras.getLong("gameId");
        
        ((TextView)findViewById(R.id.title_right_text)).setText(player.getLogin());
        
        table1 = (TableLayout)findViewById(R.id.vh_tl_table1);
        gameIdView = (TextView)findViewById(R.id.vh_tv_gameid);
        gameCityView = (TextView)findViewById(R.id.vh_tv_gamecity);
        gameStartDateView = (TextView)findViewById(R.id.vh_tv_gamestartdate);
        
        nextButton = (Button)findViewById(R.id.vh_b_next);
        previousButton = (Button)findViewById(R.id.vh_b_previous);
        
        launchViewHistoryThread();
	}

	private void doViewHistory() {

		if (fgList.length == 0) {
			setResult(CustomResultCodes.VH_NO_GAMES_RESULT_CODE);
			finish();
			return;
		}
		if (gameId != 0L) {
			for (int i=0;i<fgList.length;i++) {
				if (fgList[i].getGameId() == gameId) {
					int position = fgList[i].getPosition(player.getLogin());
					if (position == 1)
						Toast.makeText(this, "You have won the game! Congratulations! ", 
								Toast.LENGTH_LONG).show();
					else if (position != 0)
						Toast.makeText(this, "Game has finished! Final position : " + 
								String.valueOf(position), Toast.LENGTH_LONG).show();
					fillGameData(i);
				}
			}
		}
		else
			fillGameData(0);		
	}
	
	private void launchViewHistoryThread() {
		getHistoryTask = new GetHistoryTask(player.getLogin());
		Thread getHistoryThread = new Thread(null, getHistoryTask, "Login");
		getHistoryThread.start();
		showDialog(CommonDialogs.CONNECTING_TO_SERVER_DIALOG_ID);
	}

	private void setHeader(int gameNumber, int numberOfGames,
			String city, String startDate) {
		
        gameIdView.setText("Game : " + gameNumber +
        		" / " + numberOfGames);

        gameCityView.setText("City : " + city);
        gameStartDateView.setText("Start date : " + startDate);
        
        TableRow tr = new TableRow(this);

        TextView tvLogin = new TextView(this);
    	tvLogin.setText("LOGIN");
    	tvLogin.setTextColor(Color.CYAN);
    	tvLogin.setWidth(100);
    	
    	TextView tvPoints = new TextView(this);
    	tvPoints.setText("POINTS");
    	tvPoints.setTextColor(Color.CYAN);
    	tvPoints.setWidth(100);
    	
    	TextView tvItems = new TextView(this);
    	tvItems.setText("NUM. OF ITEMS");
    	tvItems.setTextColor(Color.CYAN);
    	tvItems.setWidth(100);
    	
    	tr.addView(tvLogin);
    	tr.addView(tvPoints);
    	tr.addView(tvItems);
    	tr.setPadding(0, 10, 0, 10);
    	table1.addView(tr);		
	}
	
	private void fillGameData(int gameNumber) {
		
		table1.removeAllViews();
		FinishedGame fg = fgList[gameNumber];
		setHeader(gameNumber + 1, fgList.length, 
				fg.getCity(), DateOperations.formatDate(fg.getStartDate()));
		
		if (fgList.length > (gameNumber + 1)) {
				nextButton.setVisibility(View.VISIBLE);
				nextButton.setOnClickListener(new 
						NextOnClickListener(gameNumber + 1));
		}
		else {
			nextButton.setVisibility(View.INVISIBLE);
		}
		
		if (gameNumber > 0) {
			previousButton.setVisibility(View.VISIBLE);
			previousButton.setOnClickListener(new 
					NextOnClickListener(gameNumber - 1));
		}
		else {
			previousButton.setVisibility(View.INVISIBLE);
		}

		TableRow tr;
		TextView tvLogin, tvPoints, tvItems;
		int textColor;

    	for (int i=0;i<fg.getLogins().size();i++) {
        	tr = new TableRow(this);
        	
        	if (player.getLogin().equals(fg.getLogins().get(i))) 
        		textColor = Color.GREEN;
        	else
        		textColor = Color.GRAY;
        	
        	tvLogin = new TextView(this);
        	tvLogin.setText(fg.getLogins().get(i));
        	tvLogin.setTextColor(textColor);
        	tvLogin.setWidth(100);
        	
        	tvPoints = new TextView(this);
        	tvPoints.setText(String.valueOf(fg.getPoints().get(i)));
        	tvPoints.setTextColor(textColor);
        	tvPoints.setWidth(100);
        	
        	tvItems = new TextView(this);
        	tvItems.setText(String.valueOf(fg.getItemsCaughted().get(i)));
        	tvItems.setTextColor(textColor);
        	tvItems.setWidth(100);
        	
        	tr.addView(tvLogin);
        	tr.addView(tvPoints);
        	tr.addView(tvItems);
        	
        	table1.addView(tr);
    	}
	}
	
	private void doLogout() {
		CommonActions.launchLogoutThread(player.getLogin(), this);
	}
	
	@Override
    protected Dialog onCreateDialog(int id) {
		return CommonDialogs.createDialog(id, this);
    }

	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        menu.add(0, LOGOUT_ID,0, R.string.fg_mo_logout)
        	.setIcon(R.drawable.logout);
        return true;
    }
    
    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        switch(item.getItemId()) {
        case LOGOUT_ID:
        	doLogout();
        	break;
        }
        
        return super.onMenuItemSelected(featureId, item);
    }
    
	private class GetHistoryHandler extends Handler {

		public GetHistoryHandler(Looper looper) {
			super(looper);
		}
		
		@Override
		public void handleMessage(Message msg) {
			ServerException sE = 
				(ServerException)msg.getData().getSerializable("ServerException");
			if (sE	!= null) {
				dismissDialog(CommonDialogs.CONNECTING_TO_SERVER_DIALOG_ID);
				CommonDialogs.errorMessage = sE.getMessage();
				if (sE.getCode() == ServerException.INSTANCE_NOT_FOUND_CODE)
					showDialog(CommonDialogs.CONNECTION_LOST_DIALOG_ID);
				else
					showDialog(CommonDialogs.SERVER_ERROR_DIALOG_ID);
	        	return;
	        }
        	Exception e = 
	        	(Exception)msg.getData().getSerializable("Exception");
	        	if (e != null) {
	        		dismissDialog(CommonDialogs.CONNECTING_TO_SERVER_DIALOG_ID);
	        		CommonDialogs.errorMessage = e.getLocalizedMessage();
		        	showDialog(CommonDialogs.CLIENT_ERROR_DIALOG_ID);
		        	return;
	        	}
	        FinishedGame [] fgList2 = (FinishedGame [])
	        	msg.getData().getSerializable("fgList");
	        if (fgList2 != null) {
	        	fgList = fgList2;
	        	doViewHistory();
	        	dismissDialog(CommonDialogs.CONNECTING_TO_SERVER_DIALOG_ID);
	        }
		}
	}
	
	private class GetHistoryTask implements Runnable {

		String login;
		HttpPlayerServiceImpl playerService;
		
		GetHistoryTask(String login) {
			this.login = login;
			playerService = new HttpPlayerServiceImpl();
		}
		
		public void run() {
			
			GetHistoryHandler handler = new GetHistoryHandler(Looper.getMainLooper());
			Bundle data = new Bundle();
			Message msg = new Message();
			try {
				FinishedGame [] fgList = 
					playerService.getHistory(login).toArray(
							new FinishedGame [0]);
				data.putSerializable("fgList", fgList);
				msg.setData(data);
				handler.sendMessage(msg);
				
			} catch (ServerException e) {
	        	data.putSerializable("ServerException", e);
	        	msg.setData(data);
				handler.sendMessage(msg);
	        } catch (Exception e) {
	        	data.putSerializable("Exception", e);
	        	msg.setData(data);
				handler.sendMessage(msg);
	        }
		}
	}
}
